package com.kunchi.platform.service.impl;

import com.kunchi.platform.entity.project.Project;
import com.kunchi.platform.entity.project.ProjectConf;
import com.kunchi.platform.entity.project.ProjectModule;
import com.kunchi.platform.repository.ProjectConfRepository;
import com.kunchi.platform.repository.ProjectModuleRepository;
import com.kunchi.platform.repository.ProjectRepository;
import com.kunchi.platform.service.ProjectService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by denniszhou on 2017/7/23.
 */
@Service("projectService")
public class ProjectServiceImpl implements ProjectService {
  @Autowired
  ProjectRepository projectRepository;

  @Autowired
  ProjectConfRepository projectConfRepository;

  @Autowired
  ProjectModuleRepository projectModuleRepository;

  @Override
  public List<Project> findByCompanyId(Long companyId) {
    return projectRepository.findByCompanyId(companyId);
  }

  @Override
  public Project findById(Long id) {
    return projectRepository.findOne(id);
  }

  @Override
  public ProjectConf createConfiguration(ProjectConf projectConf) {
    if (projectConf.isDefaultValue()) {
      projectConfRepository.findByProjectId(projectConf.getProjectId()).forEach(s -> {
        s.setDefaultValue(false);
        projectConfRepository.save(s);
      });
    }
    return projectConfRepository.save(projectConf);
  }

  @Override
  public ProjectConf saveConfiguration(Long id, String content, String picture) {
    ProjectConf projectConf = projectConfRepository.findOne(id);
    projectConf.setContent(content);
    projectConf.setPicture(picture);
    return projectConfRepository.save(projectConf);
  }

  @Override
  public void deleteConfiguration(Long id) {
    projectConfRepository.delete(id);
  }

  @Override
  public List<ProjectConf> findConfigurationsByProjectId(Long projectId) {
    return projectConfRepository.findByProjectId(projectId);
  }

  @Override
  public ProjectConf findConfigurationByIdAndProjectId(Long id, Long projectId) {
    return projectConfRepository.findByIdAndProjectId(id, projectId);
  }

  @Override
  public Project createProject(Project project) {
    return projectRepository.save(project);
  }

  @Override
  public ProjectModule findProjectModuleByProjectId(Long projectId) {
    ProjectModule module = projectModuleRepository.findOne(projectId);
    return module == null ? new ProjectModule(projectId, true, true, true, true, true, true) : module;
  }

  @Override
  public ProjectModule updateProjectModule(ProjectModule projectModule) {
    return projectModuleRepository.save(projectModule);
  }

}
